//
//  M4FiveInfosViewController.swift
//  M4
//
//  Created by YuChuang on 2024/8/15.
//

import UIKit
import AVFoundation

class M4FiveInfosViewController: M4BaseViewController {
    
    @IBOutlet weak var M4FiveBackButton: UIButton!
    @IBOutlet weak var M4FiveTakeImageView: UIImageView!
    
    @IBOutlet weak var M4FiveShibieView: UIView!
    
    @IBOutlet weak var M4FiveShibieImageView: UIImageView!
    
    @IBOutlet weak var M4FiveCompeletView: UIView!
    
    @IBOutlet weak var M4FiveTakePhotoButton: UIButton!
    
    @IBOutlet weak var M4FiveResetCameraButton: UIButton!
    
    @IBOutlet weak var M4FiveTakeSuccessButton: UIButton!
    
    private var M4FiveCaptureOutput: AVCaptureVideoDataOutput = AVCaptureVideoDataOutput()
    
    private var M4FiveCaptureSession: AVCaptureSession?
    
    private var M4FiveTakePicture: Bool = false
    
    private var M4FiveImageData: Data = Data()
    
    private var m4enterTime: Int = 0
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.isHidden = false
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        m4enterTime = Int(Date().timeIntervalSince1970 * 1000)
        let momAnimation = CABasicAnimation(keyPath:"transform.rotation.z")
        momAnimation.fromValue = NSNumber(value:0)
        momAnimation.toValue = NSNumber(value:Double.pi*2)
        momAnimation.duration = 1
        momAnimation.repeatCount = HUGE
        M4FiveShibieImageView.layer.add(momAnimation, forKey:"M4FiveLoadingLayer")
        M4FiveCheckCameraLimit()
    }
    
    private func M4FiveCheckCameraLimit() {
        AVCaptureDevice.requestAccess(for: .video) { granted in
            if granted {
                self.asfqwr = 1
                DispatchQueue.main.async {
                    self.M4FiveSetupCamera()
                }
            }
            else {
                self.asfqwr = 0
                DispatchQueue.main.async {
                    let alert = UINib(nibName: "M4LimitAlertView", bundle: nil).instantiate(withOwner: self).last as! M4LimitAlertView
                    alert.M4LimitAlertViewUpdate(nameArray: [["img": "icon_limit_camera", "name": "Cámara"]])
                    alert.M4LimitCloseBlock = {
                        self.navigationController?.popToRootViewController(animated: true)
                    }
                    self.view.addSubview(alert)
                    alert.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
                    UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseInOut) {
                        alert.alpha = 1
                        alert.transform = CGAffineTransform.identity
                    }
                    alert.M4DecriptionView.c = self
            //        alert.M4AlertViewShow()
                }
            }
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        M4FiveSettingMaskLayer()
    }
    
    @IBAction func M4FiveBackClick(_ sender: UIButton) {
        //人脸图片上传加载中， 不可返回
        if M4FiveShibieView.isHidden == false { return }
        M4InfosPageBack()
        sender.M4EventUnavailable = false
        
        uploadData()
    }
    
    @IBAction func M4FiveTakeClick(_ sender: UIButton) {
        M4FiveTakePicture = true
        M4FiveUpdateButton(isTake: false)
        sender.M4EventUnavailable = false
        
        gtsds = Int(Date().timeIntervalSince1970 * 1000)
    }
    
    @IBAction func M4FiveResetClick(_ sender: UIButton) {
        M4FiveTakePicture = false
        M4FiveCaptureSession?.startRunning()
        M4FiveUpdateButton(isTake: true)
        sender.M4EventUnavailable = false
    }
    
    @IBAction func M4FiveTakeSuccessClick(_ sender: UIButton) {
        let dataStr: String = M4FiveImageData.base64EncodedString(options: [])
        self.M4FaceFielUpload(imgStr: dataStr)
        sender.M4EventUnavailable = false
    }
    
    private func M4FiveUpdateButton(isTake: Bool) {
        M4FiveTakePhotoButton.isHidden = isTake ? false : true
        M4FiveResetCameraButton.isHidden = isTake ? true : false
        M4FiveTakeSuccessButton.isHidden = isTake ? true : false
    }
    
    private func M4FiveLoadingShow() {
        self.M4FiveBackButton.isEnabled = false
        self.M4FiveResetCameraButton.isEnabled = false
        M4FiveShibieView.isHidden = false
        UIView.animate(withDuration: 0.2, delay: 0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.25) {
            self.M4FiveShibieView.alpha = 1
            self.M4FiveShibieView.transform = CGAffineTransform.identity
        }
    }
    
    private func M4FiveLoadingHide(completion: @escaping () -> Void) {
        UIView.animate(withDuration: 0.3) {
            self.M4FiveShibieView.alpha = 0.2
            self.M4FiveShibieView.transform = self.M4FiveShibieView.transform.scaledBy(x: 0.4, y: 0.4)
        } completion: { r in
            self.M4FiveShibieView.alpha = 0
            self.M4FiveShibieView.isHidden = true
            self.M4FiveBackButton.isEnabled = true
            self.M4FiveResetCameraButton.isEnabled = true
            completion()
        }
    }
    
    var asfqwr = 0
    var gtsds = 0
    func uploadData() {
        let params: [[String:Any]] = [
            [
                "adga" : 7001,
                "sdqw" : inTime,
                "hgjyj" : Int(Date().timeIntervalSince1970 * 1000) ,
                "asfqwr" : asfqwr,
                "gtsds" : gtsds
            ]
        ]
        M4HiddenPointDataManager.M4UploadHiddenPoint(type: .Face, paramsKey: "gqyqy", params: params, complete: nil)
    }
}

extension M4FiveInfosViewController: AVCaptureVideoDataOutputSampleBufferDelegate {
    
    func M4FiveSettingMaskLayer() {
        for l in self.view.layer.sublayers ?? [] {
            if l is CAShapeLayer {
                return
            }
        }
        self.view.layoutIfNeeded()
        M4FiveTakeImageView.layoutIfNeeded()
        M4FiveTakeImageView.backgroundColor = .clear
        let path2 = UIBezierPath(roundedRect: M4FiveTakeImageView.frame, cornerRadius: 5)
        let path = UIBezierPath(rect: self.view.bounds)
        path.append(path2)
        path.usesEvenOddFillRule = true
        
        let layer1 = CAShapeLayer()
        layer1.frame = self.view.bounds
        layer1.path = path.cgPath
        layer1.fillColor = UIColor.black.cgColor
        layer1.opacity = 0.5
        layer1.fillRule = .evenOdd
        self.view.layer.insertSublayer(layer1, below: M4FiveTakeImageView.layer)
    }
    
    private func M4FiveSetupCamera() {
        M4FiveCaptureSession = AVCaptureSession()
        M4FiveCaptureSession?.sessionPreset = .photo
        M4FiveCaptureSession?.beginConfiguration()
        guard let M4ThirdCaptureDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .front),
        let captureInput = try? AVCaptureDeviceInput(device: M4ThirdCaptureDevice) else {return}
        if M4FiveCaptureSession?.canAddInput(captureInput) == true {
            M4FiveCaptureSession?.addInput(captureInput)
        }
        M4FiveCaptureOutput.videoSettings = [(kCVPixelBufferPixelFormatTypeKey as NSString):NSNumber(value:kCVPixelFormatType_32BGRA)] as [String : Any]
        M4FiveCaptureOutput.alwaysDiscardsLateVideoFrames = true
        if M4FiveCaptureSession?.canAddOutput(M4FiveCaptureOutput) == true {
            M4FiveCaptureSession?.addOutput(M4FiveCaptureOutput)
        }
        let queue = DispatchQueue(label: "com.brianadvent.captureQueue")
        M4FiveCaptureOutput.setSampleBufferDelegate(self, queue: queue)
        M4FiveCaptureSession?.commitConfiguration()
        let captureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: M4FiveCaptureSession ?? AVCaptureSession())
        captureVideoPreviewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
        captureVideoPreviewLayer.frame = CGRect(x: 0, y: 0, width: M4ScreenWidth, height:M4ScreenHeight)
        let bgLayer1 = CAGradientLayer()
        bgLayer1.name = "captureVideoPreviewColor"
        bgLayer1.colors = [COLOR_000000.withAlphaComponent(0).cgColor, COLOR_000000.withAlphaComponent(0.5).cgColor]
        bgLayer1.locations = [0, 1]
        bgLayer1.frame = CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height)
        bgLayer1.startPoint = CGPoint(x: 0.5, y: 0)
        bgLayer1.endPoint = CGPoint(x: 0.5, y: 1)
        bgLayer1.zPosition = 1
        captureVideoPreviewLayer.insertSublayer(bgLayer1, at: 0)
        self.view.layer.insertSublayer(captureVideoPreviewLayer, at: 0)
        DispatchQueue.global(qos: .background).async {
            self.M4FiveCaptureSession?.startRunning()
        }
    }
        
    func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
        if M4FiveTakePicture {
            self.M4FiveCaptureSession?.stopRunning()
            DispatchQueue.main.async {
                let originImage = M4Image.M4SampleBuffer(sbuffer: sampleBuffer, orientation: .right)
                if originImage == nil {
                    self.M4FiveTakePhotoButton.M4EventUnavailable = false
                    self.M4FiveTakePicture = false
                    self.M4FiveCaptureSession?.startRunning()
                    return
                }
//                originImage = M4Image.M4ImageCropped(originImg: originImage ?? UIImage(), croppedView: self.view)
                guard let imgData = M4Image.M4ImageCompress(image: originImage ?? UIImage(), maxSize: 10*1024*1024) else {return}
                self.M4FiveImageData = imgData
            }
        }
    }
    
}

class ImageTestViewController: UIViewController {
    
    var imageData: Data?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let imageView = UIImageView()
        if imageData != nil {
            imageView.image = UIImage(data: imageData!)
        }
        imageView.contentMode = .scaleAspectFit
        view.addSubview(imageView)
        imageView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalToSuperview().offset(-36)
            make.height.equalToSuperview().offset(240)
        }
    }
    
}


extension M4FiveInfosViewController {
    
    private func M4FaceFielUpload(imgStr: String) {
        M4FiveLoadingShow()
        M4PublicNetwork.M4UploadFielNet(imgBase64Str: imgStr) { success, urlstring in
            if success {
                self.M4SubmitFiveInfoNet(fielString: urlstring)
            }
            else {
                self.M4FiveLoadingHide {
                    let alert = UINib(nibName: "M4FaceFailAlertView", bundle: nil).instantiate(withOwner: self).last as! M4FaceFailAlertView
                    alert.M4FaceFailUpdateUI(title: "Fallo en el reconocimiento facial", content: "Por favor, asegúrese de que hay\nsuficiente luz y vuelva a intentarlo", buttonTitle: "Vuelva a intentarlo")
                    alert.M4FaceFailBlock = {
                        self.M4FiveTakePicture = false
                        self.M4FiveCaptureSession?.startRunning()
                        self.M4FiveUpdateButton(isTake: true)
                    }
                    alert.M4AlertViewShow()
                }
            }
        }
    }
    
    private func M4SubmitFiveInfoNet(fielString: String) {
        let m4endTime = Int(Date().timeIntervalSince1970 * 1000) - m4enterTime
        let param1: [String : Any] = ["FeqKW": M4UserDataManager.m4UserShare.M4Itemcode, "YOcQCpfM": "ESP", "KKo": M4UserDataManager.m4UserShare.M4ProductCode, "CAdRudKdvHw": M4UserDataManager.m4UserShare.M4Token, "Zucl": 6, "ZFYBivZHpZD": m4endTime, "OCPa": fielString]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4submitCreditInfo, .post, params: param1)) { model in
            if model.code == 1 {
                self.M4FiveLoadingHide {
                    self.M4FiveCompeletView.isHidden = false
                    UIView.animate(withDuration: 0.2, delay: 0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.25) {
                        self.M4FiveCompeletView.alpha = 1
                        self.M4FiveCompeletView.transform = CGAffineTransform.identity
                    }
                    UIView.animate(withDuration: 0.3) {
                        self.M4FiveCompeletView.alpha = 0.2
                        self.M4FiveCompeletView.transform = self.M4FiveCompeletView.transform.scaledBy(x: 0.4, y: 0.4)
                    } completion: { r in
                        self.M4FiveCompeletView.alpha = 0
                        self.M4FiveCompeletView.isHidden = true
                        M4LimitVerification().M4LimitDataAsk1 { arrayCount in
                            if arrayCount.count > 0 {
                                M4LimitVerification().M4_showAskAlert(arr: arrayCount) { _ in }
                            }
                            else {
                                //上传埋点，跳转提单页
                                if M4UserDataManager.M4HasShowUploadPage == false {
                                    M4PublicNetwork.M4ShowUploadAlert { r in
                                        self.M4UploadDataDone(issuccess: r)
                                    }
                                } else {
                                    
                                    M4PublicNetwork.M4ShowUploadAlert { r in
                                        self.M4UploadDataDone(issuccess: r)
                                    }
                                    
//                                    M4PublicNetwork.M4VerficationPointDataNet { issuccess in
//                                        self.M4UploadDataDone(issuccess: issuccess)
//                                    }
                                }
                            }
                        }
                    }
                }
                
                self.uploadData()
            }
            else {
                self.M4FiveLoadingHide {
                    let alert = UINib(nibName: "M4FaceFailAlertView", bundle: nil).instantiate(withOwner: self).last as! M4FaceFailAlertView
                    alert.M4FaceFailUpdateUI(title: "Fallo en el reconocimiento facial", content: "Por favor, asegúrese de que hay\nsuficiente luz y vuelva a intentarlo", buttonTitle: "Vuelva a intentarlo")
                    alert.M4FaceFailBlock = {
                        self.M4FiveTakePicture = false
                        self.M4FiveCaptureSession?.startRunning()
                        self.M4FiveUpdateButton(isTake: true)
                    }
                    alert.M4AlertViewShow()
                }
            }
        }
    }
    
    func M4UploadDataDone(issuccess: Bool) {
        if issuccess {
            let page = M4ProductDetailViewController()
            self.navigationController?.pushViewController(page, animated: true)
        }
        else {
            if self.navigationController?.viewControllers.first is M4FirstInfoViewController {
                AppDelegate.keyWindow()?.rootViewController = M4TabBarViewController()
            }
            else {
                self.navigationController?.popToRootViewController(animated: true)
            }
        }
    }
    
}
